package com.dbh.alg.datastructure.priorityqueue;

import com.dbh.alg.datastructure.queue.Queue;

public class PriorityQueue2<E extends Priority> implements Queue<E> {

    Priority[] array;

    int size;

    public PriorityQueue2(int capacity) {
        array = new Priority[capacity];
    }

    @Override
    public boolean offer(E value) {
        if (isFull()) {
            return false;
        }
        insert(value);
        size++;
        return true;
    }

    private void insert(E e) {
        int i = size - 1;
        while (i >= 0 && array[i].priority() > e.priority()) {
            array[i + 1] = array[i];
            i--;
        }
        array[i + 1] = e;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        return  (E) array[--size];
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return  (E) array[size-1];
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == array.length;
    }

    public static void main(String[] args) {
        Task task1 = new Task(1);
        Task task2 = new Task(2);
        Task task4 = new Task(4);
        Task task3 = new Task(3);
        PriorityQueue2<Task> priorityQueue1 = new PriorityQueue2<Task>(4);
        priorityQueue1.offer(task1);
        priorityQueue1.offer(task2);
        priorityQueue1.offer(task4);
        priorityQueue1.offer(task3);
        System.out.println(priorityQueue1.poll().priority());;
        System.out.println(priorityQueue1.poll().priority());;
        System.out.println(priorityQueue1.poll().priority());;
        System.out.println(priorityQueue1.poll().priority());;
    }
}
